<?php
session_start();
include '../conn.php';
include 'function.php';

if (!isset($_REQUEST['uid'])) {
    echo "非法访问！";
    exit;
}
$uid = $_REQUEST['uid'];

// 查询用户是否存在
$sql = "SELECT * FROM user WHERE id = " . $uid;
$result = $conn->query($sql);

if ($result->num_rows <= 0) {
    echo '请先注册或登录！';
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>我的订单</title>
  <link rel="stylesheet" type="text/css" href="../css/general.css">
  <link rel="stylesheet" type="text/css" href="../css/index.css">
  <link rel="stylesheet" type="text/css" href="../css/table.css">
  <script type="text/javascript" src="../js/jquery.js"></script>
  <script type="text/javascript" src="../js/general.js"></script>
  <script type="text/javascript" src="../js/carousel.js"></script>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }
    th, td {
      border: 1px solid #ddd;
      padding: 8px;
    }
    th {
      background-color: #f2f2f2;
    }
  </style>
</head>
<body>
<!-- 头部开始 -->
<div class="header-body">
    <!-- 头部开始 -->
    <?php include 'header.php'; ?>
    <!-- 头部结束 -->
</div>
<!-- 头部结束 -->
<!-- 主体开始 -->
<div class="container">
    <h1>我的订单</h1>
    <table>
        <tr>
            <th>订单ID</th>
            <th>商品名</th>
            <th>数量</th>
            <th>单价</th>
            <th>总价</th>
        </tr>
        <?php
        // 连接查询订单数据
        $sql = "SELECT o.id AS order_id, g.goods_name, o.count, g.price, (o.count * g.price) AS total_price
                FROM orders o
                JOIN goods g ON o.goods_id = g.id
                WHERE o.user_id = " . $uid;
        $result = $conn->query($sql);

        // 检查查询是否成功
        if ($result === false) {
            die("查询失败: " . $conn->error);
        }

        // 打印查询结果，方便排查
        echo "<pre>";
        if ($result->num_rows > 0) {
        } else {
            echo "查询结果为空";
        }
        echo "</pre>";

        if ($result->num_rows > 0) {
            $result->data_seek(0); // 重置结果指针
            while ($row = $result->fetch_assoc()) {
        ?>
        <tr>
            <td><?php echo htmlspecialchars($row['order_id']); ?></td>
            <td><?php echo htmlspecialchars($row['goods_name']); ?></td>
            <td><?php echo htmlspecialchars($row['count']); ?></td>
            <td><?php echo htmlspecialchars($row['price']); ?></td>
            <td><?php echo htmlspecialchars($row['total_price']); ?></td>
        </tr>
        <?php
            }
        } else {
            echo "<tr><td colspan='5'>没有订单</td></tr>";
        }
        ?>
    </table>
</div>
<!-- 主体结束 -->

<!-- 页脚开始 -->
<div style="margin-top:200px;"></div>
<?php include '../footer.php'; ?>
<!-- 页脚结束 -->

</body>
</html>